<template>
  <div class="personal-center">
    <!-- 左侧导航栏 -->
    <div class="nav-sidebar">
      <el-menu
        :default-active="activeMenu"
        class="nav-menu"
        @select="handleSelect">
        <el-menu-item index="1">
          <el-icon><User /></el-icon>
          <span>个人信息</span>
        </el-menu-item>
        <el-menu-item index="2">
          <el-icon><Lock /></el-icon>
          <span>修改密码</span>
        </el-menu-item>
        <el-menu-item index="3">
          <el-icon><Star /></el-icon>
          <span>收藏夹</span>
        </el-menu-item>
        <el-menu-item index="4">
          <el-icon><Bell /></el-icon>
          <span>通知中心</span>
        </el-menu-item>
        <el-menu-item index="5">
          <el-icon><Connection /></el-icon>
          <span>关注/粉丝</span>
        </el-menu-item>
        <el-menu-item index="6">
          <el-icon><EditPen /></el-icon>
          <span>笔记</span>
        </el-menu-item>
        <el-menu-item v-if="userInfo.role === 'teacher'" index="7">
          <el-icon><Briefcase /></el-icon>
          <span>教师工作区</span>
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 右侧内容区 -->
    <div class="content-area">
      <!-- 个人信息内容 -->
      <div v-if="activeMenu === '1'" class="info-content">
        <el-card class="info-card">
          <div slot="header" class="card-header">
            <span>个人信息</span>
          </div>
          <div v-loading="loading">
            <div class="info-item">
              <label>用户名：</label>
              <span>{{ userInfo.username }}</span>
            </div>
            <div class="info-item">
              <label>用户ID：</label>
              <span>{{ userInfo.id }}</span>
            </div>
            <div class="info-item">
              <label>角色：</label>
              <span>{{ userInfo.role === 'teacher' ? '教师' : '学生' }}</span>
            </div>
            <div class="info-item">
              <label>邮箱：</label>
              <span>{{ userInfo.email }}</span>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 修改密码内容 -->
      <div v-if="activeMenu === '2'" class="password-content">
        <el-card class="password-card">
          <div slot="header" class="card-header">
            <span>修改密码</span>
          </div>

          <!-- 第一步：发送验证码 -->
          <div v-if="!showResetForm" class="send-code-step">
            <p class="step-info">第一步：发送验证码到邮箱 {{ userInfo.email }}</p>
            <div class="send-code-button">
              <el-button
                type="primary"
                @click="requestVerificationCode"
                :loading="sendingCode"
                :disabled="isButtonDisabled">
                {{ buttonText }}
              </el-button>
            </div>
          </div>

          <!-- 第二步：重置密码表单 -->
          <el-form
            v-if="showResetForm"
            :model="passwordForm"
            :rules="passwordRules"
             ref="passwordFormRef"
            label-width="100px">
            <div class="step-info">第二步：输入验证码和新密码</div>
            <el-form-item label="验证码" prop="token">
              <el-input
                v-model="passwordForm.token"
                placeholder="请输入邮箱收到的验证码">
              </el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                type="password"
                v-model="passwordForm.newPassword"
                show-password>
              </el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                type="password"
                v-model="passwordForm.confirmPassword"
                show-password>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitPasswordChange">确认修改</el-button>
              <el-button @click="resetPasswordForm">重置</el-button>
              <el-button type="text" @click="backToSendCode">返回上一步</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <!-- 收藏夹内容 -->
      <div v-if="activeMenu === '3'" class="favorites-content">
        <FavoritesList :user-info="userInfo" />
      </div>

      <!-- 通知中心内容 -->
      <div v-if="activeMenu === '4'" class="notification-content">
        <NotificationList :user-info="userInfo" />
      </div>

      <!-- 关注/粉丝内容 -->
      <div v-if="activeMenu === '5'" class="follow-content">
        <FollowList :user-info="userInfo" />
      </div>

      <!-- 笔记内容 -->
      <div v-if="activeMenu === '6'" class="notes-content">
        <NoteView :user-info="userInfo" />
      </div>

      <!-- 工作区内容 -->
      <div v-if="activeMenu === '7'" class="workspace-content">
        <TeacherWorkspace :user-info="userInfo" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { User, Lock, Star, Bell, Connection, EditPen, Briefcase } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import FavoritesList from './FavoritesList.vue'
import NotificationList from "@/components/notice/NotificationList.vue"
import FollowList from "@/components/PersonalCenter/FollowList.vue"
import TeacherWorkspace from "@/components/TeacherWorkspace/TeacherWorkspace.vue"
import NoteView from "@/components/Note/NoteView.vue"

const activeMenu = ref('1')
const loading = ref(true)
const sendingCode = ref(false)
const countdown = ref(60)
const timer = ref(null)
const isButtonDisabled = ref(false)
const buttonText = ref('发送验证码')
const showResetForm = ref(false)
const passwordFormRef = ref(null)  // 修改：添加表单引用

const userInfo = ref({
  username: '',
  id: '',
  role: '',
  email: ''
})

const passwordForm = ref({
  token: '',
  newPassword: '',
  confirmPassword: ''
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== passwordForm.value.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  token: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const fetchUserInfo = async () => {
  try {
    loading.value = true
    const response = await axios.get('/backend/api/account/profile/')
    userInfo.value = response.data
  } catch (error) {
    ElMessage.error('获取用户信息失败')
    console.error('获取用户信息错误:', error)
  } finally {
    loading.value = false
  }
}

const handleSelect = (key) => {
  activeMenu.value = key
  if (key === '2') {
    showResetForm.value = false
  }
}

const startCountdown = () => {
  isButtonDisabled.value = true
  countdown.value = 60
  buttonText.value = `${countdown.value}秒后重试`

  timer.value = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
      buttonText.value = `${countdown.value}秒后重试`
    } else {
      clearInterval(timer.value)
      isButtonDisabled.value = false
      buttonText.value = '发送验证码'
    }
  }, 1000)
}

const requestVerificationCode = async () => {

  try {
    sendingCode.value = true
    await axios.post('/backend/api/account/password/reset_request/', {
      id: userInfo.value.id
    })
    ElMessage.success('验证码已发送到您的邮箱')
    startCountdown()
    showResetForm.value = true
  } catch (error) {
    ElMessage.error('验证码发送失败')
    console.error('发送验证码错误:', error)
  } finally {
    sendingCode.value = false
  }
}

// 修改：更新表单验证和提交逻辑
const submitPasswordChange = async () => {
  if (!passwordFormRef.value) return

  try {
    const valid = await passwordFormRef.value.validate()
    if (valid) {
      await axios.post('/backend/api/account/password/reset/', {
        id: userInfo.value.id,
        token: passwordForm.value.token,
        new_password: passwordForm.value.newPassword
      })
      ElMessage.success('密码修改成功')
      resetPasswordForm()
      showResetForm.value = false
    }
  } catch (error) {
    if (error.message) {
      ElMessage.error('表单验证失败')
    } else {
      ElMessage.error('密码修改失败')
      console.error('修改密码错误:', error)
    }
  }
}

const resetPasswordForm = () => {
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }
}

const backToSendCode = () => {
  showResetForm.value = false
  resetPasswordForm()
}

onMounted(() => {
  fetchUserInfo()
})
</script>


<style scoped>
.personal-center {
  display: flex;
  min-height: calc(100vh - 60px);
  background-color: #f0f2f5;
}

.nav-sidebar {
  width: 200px;
  background-color: #fff;
  border-right: 1px solid #e6e6e6;
}

.nav-menu {
  border-right: none;
}

.content-area {
  flex: 1;
  padding: 20px;
  position: relative;
}

.info-card, .password-card {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  font-size: 16px;
  font-weight: bold;
}

.info-item {
  margin-bottom: 15px;
  line-height: 24px;
  padding-left: 40px;
  text-align: left;
}

.info-item label {
  display: inline-block;
  width: 80px;
  color: #606266;
  font-weight: 500;
}

.info-item span {
  color: #303133;
  margin-left: 20px;
}

.password-content .el-form {
  max-width: 400px;
  margin: 0 auto;
}

.send-code-step {
  text-align: center;
  padding: 20px;
}

.step-info {
  color: #606266;
  margin-bottom: 20px;
  font-size: 14px;
}

.send-code-button {
  margin: 20px 0;
}
</style>